/*********************************************************************************
 *      Copyright:  (C) 2024 LingYun<iot25@lingyun>
 *                  All rights reserved.
 *
 *       Filename:  get_temperature.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/12/24)
 *         Author:  LingYun <iot25@lingyun>
 *      ChangeLog:  1, Release initial version on "07/12/24 17:54:13"
 *                 
 ********************************************************************************/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include "get_temperature.h"

float get_temperature()
{
	int 			fd = -1;
    float 			templ;
    float 			temperature;
    char 			buf[128];
    char 			*ptr = NULL;
    char 			w1_path[64] = "/sys/bus/w1/devices/";
    DIR 			*dirp = NULL;
    struct dirent 	*direntp = NULL;
    char 			chip_sn[32];
    int 			found = 0;

    dirp = opendir(w1_path);
    if (!dirp)
    {
        printf("Open folder %s failure: %s\n", w1_path, strerror(errno));
        return -1;
    }

    direntp = readdir(dirp);
    if (!direntp)
    {
        printf("Read folder %s failure: %s\n", w1_path, strerror(errno));
        closedir(dirp);
        return -2;
    }
    while (NULL != (direntp = readdir(dirp)))
    {
        if (strstr(direntp->d_name, "28-")) // 找到"28-"开头的文件夹
        {
            strncpy(chip_sn, direntp->d_name, sizeof(chip_sn)); // 将找到的文件夹名复制到chip_sn
            found = 1;
        }
    }
    closedir(dirp);

    if (!found)
    {
        printf("Can not find ds18b20 chipset\n");
        return -3;
    }

    strncat(w1_path, chip_sn, sizeof(w1_path) - strlen(w1_path) - 1);
    strncat(w1_path, "/w1_slave", sizeof(w1_path) - strlen(w1_path) - 1);
    // printf("w1_path:%s\n",w1_path);

    fd = open(w1_path, O_RDONLY);
    if (fd < 0)
    {
        printf("Open file failure: %s\n", strerror(errno));
        return -4;
    }

    memset(buf, 0, sizeof(buf));
    if (read(fd, buf, sizeof(buf)) < 0)
    {
        printf("Read file failure: %s\n", strerror(errno));
        close(fd);
        return -5;
    }
    close(fd);

    ptr = strstr(buf, "t=");
    if (NULL == ptr)
    {
        printf("Can not find t= string\n");
        return -6;
    }

    ptr += 2;
    // printf("ptr: %s\n",ptr);

    templ = atof(ptr);
    // printf("templ:%f\n",templ);
    temperature = templ / 1000;
    // printf("函数里面temperature:%f\n",temperature);
    // printf("buf:%s\n",buf);
    return temperature;
}


